package com.szhn.bookservice.controller;


import com.szhn.bookservice.entity.Book;
import com.szhn.bookservice.entity.vo.BookCondition;
import com.szhn.bookservice.feignclients.OssClient;
import com.szhn.bookservice.service.BookService;
import com.szhn.common.responsejson.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 书籍 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-10-28
 */
@RestController
@RequestMapping("/bookservice/book")
@CrossOrigin
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private OssClient ossClient;


    @ApiOperation("根据id查询书籍")
    @GetMapping("getById/{id}")
    public R getById(@PathVariable String id) {
        Book book = bookService.getById(id);
        return book != null ? R.ok().data("book", book) : R.error();
    }



    @ApiOperation("条件分页查询")
    @PostMapping("getPageByCondition/{current}/{limit}")
    public R getPageByCondition(@RequestBody(required = false) BookCondition bookCondition,
                                @PathVariable long limit,
                                @PathVariable long current
    ) {
        R r = bookService.getBookPageByCondition(bookCondition, limit, current);
        return r;
    }


    @ApiOperation("添加书籍信息")
    @PostMapping("addBook")
    public R addBook(@RequestBody Book book){
        boolean save = bookService.save(book);
        return save ? R.ok() : R.error();
    }




    @ApiOperation("根据id删除书籍信息和oss中图片内容")
    @DeleteMapping("deleteById/{id}")
    public R deleteById(@PathVariable String id){
        Book book = bookService.getById(id);
        String cover = book.getCover();
        String content = book.getContent();
        for (int i = 0; i < 3; i++) {
            int indexOf = cover.indexOf("/");
            cover = cover.substring(indexOf + 1);
        }
        for (int i = 0; i < 3; i++) {
            int indexOf = content.indexOf("/");
            content = content.substring(indexOf + 1);
        }
        ossClient.delete(content);
        ossClient.delete(cover);
        boolean flag = bookService.removeById(id);
        return flag ? R.ok() : R.error();
    }



    @ApiOperation("修改书籍信息")
    @PostMapping("update")
    public R delete(@RequestBody Book book){
        boolean update = bookService.updateById(book);
        return update ? R.ok() : R.error();
    }

}

